package com.ruoyi.safe.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.domain.entity.CommonCheckType;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.mapper.TQualityFileItemMapper;
import com.ruoyi.quality.service.ITQualityFileService;
import com.ruoyi.safe.constant.AccidentHiddenConstants;
import com.ruoyi.safe.constant.DictTypeConstants;
import com.ruoyi.safe.domain.BizProjectCheck;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.BizRectifyReview;
import com.ruoyi.safe.domain.CommonProject;
import com.ruoyi.safe.domain.dto.EntityIdAppDTO;
import com.ruoyi.safe.domain.dto.StatisticsDto;
import com.ruoyi.safe.domain.vo.ListRequestVo;
import com.ruoyi.safe.mapper.*;
import com.ruoyi.safe.service.IBizProjectCheckService;
import com.ruoyi.safe.service.ICommonCheckTypeService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目自检Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-17
 */
@Service
public class BizProjectCheckServiceImpl implements IBizProjectCheckService
{
    @Autowired
    BizProjectCheckMapper bizProjectCheckMapper;
    @Autowired
    CommonCheckTypeMapper commonCheckTypeMapper;
    @Autowired
    ICommonCheckTypeService commonCheckTypeService;
    @Autowired
    BizProjectCheckRecordMapper bizProjectCheckRecordMapper;
    @Autowired
    BizRectifyReviewMapper bizRectifyReviewMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    TQualityFileItemMapper tQualityFileItemMapper;

    @Autowired
    CommonProjectMapper commonProjectMapper;

    @Autowired
    private ITQualityFileService iTQualityFileService;
    /**
     * 查询项目自检
     *
     * @param id 项目自检主键
     * @return 项目自检
     */
    @Override
    public BizProjectCheck selectBizProjectCheckById(Long id)
    {
        BizProjectCheck bizProjectCheck = bizProjectCheckMapper.selectBizProjectCheckById(id);
        //项目名称
        CommonProject commonProject = commonProjectMapper.selectCommonProjectById(Long.valueOf(bizProjectCheck.getProjectId()));
        if(commonProject != null){
            bizProjectCheck.setProjectName(commonProject.getName());
        }
        //检查类型
        CommonCheckType commonCheckType = commonCheckTypeMapper.selectCommonCheckTypeById(bizProjectCheck.getCheckType());
        if(commonCheckType != null){
            bizProjectCheck.setCheckTypeName(commonCheckType.getCheckTypeName());
        }
        //检查依据
        if(bizProjectCheck.getCheckAccording() != null){
            bizProjectCheck.setCheckAccordingName(DictUtils.getDictLabel("check_according",String.valueOf(bizProjectCheck.getCheckAccording())));
        }
//        List<TQualityFileItem> recordList = tQualityFileItemMapper.selectTQualityFileItemById(bizProjectCheck.getId());
        List list = new ArrayList();
        list.add(bizProjectCheck.getId());
        List<TQualityFileItem> recordList  = tQualityFileItemMapper.qualityList(bizProjectCheck.getProjectId(),list);
        if(recordList.size() > 0){
            //质量问题数量
            List<TQualityFileItem> findBizProjectCheckRecords = recordList.stream().collect(Collectors.toList());
            long findDangerCount = findBizProjectCheckRecords.size();
            bizProjectCheck.setFindDangerCount(findDangerCount);
        }else {
            bizProjectCheck.setFindDangerCount(0l);
            bizProjectCheck.setImportHiddenDangerCount(0l);
        }
        //检查人名称
        if(StringUtils.isNotEmpty(bizProjectCheck.getCheckPeople())){
            NameUtils.handleUserNameToNickName(Arrays.asList(bizProjectCheck),sysUserMapper.selectUserListAll(),new String[]{"checkPeople"},new String[]{"checkPeopleName"});
        }
        return bizProjectCheck;
    }

    /**
     * 查询项目自检列表
     *
     * @param bizProjectCheck 项目自检
     * @return 项目自检
     */
    @Override
    public List<BizProjectCheck> selectBizProjectCheckList(BizProjectCheck bizProjectCheck) {
        // 如果项目id为空，显示空列表
        if (bizProjectCheck.getProjectId() == null) {
            return new ArrayList<>();
        }
        /*查询当前项目所有日志*/
        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckMapper.selectBizProjectCheckList(bizProjectCheck);
        if(bizProjectCheckList.size() == 0){
            return new ArrayList<>();
        }
        /*转存项目之日idList*/
        List<Long> bizProjectCheckIds = bizProjectCheckList.stream().map(item->item.getId()).collect(Collectors.toList());
        //关联日志id 查询所有质量问题记录
        List<TQualityFileItem> tQualityFileItems  = tQualityFileItemMapper.selectTQualityFileItemByIds(bizProjectCheckIds.toArray(new Long[0]));
        //根据日志id分组
        Map<Long,List<TQualityFileItem>> bizProjectCheckRecordMap = tQualityFileItems.stream().collect(Collectors.groupingBy(TQualityFileItem::getFileId));
        //查询所有的复查整改记录
        Set<Long> bizProjectCheckRecordIds = tQualityFileItems.stream().map(item->item.getId()).collect(Collectors.toSet());
        List<BizRectifyReview> bizRectifyReviews = new ArrayList<>();
        if(bizProjectCheckRecordIds.size() > 0){
            bizRectifyReviews = bizRectifyReviewMapper.selectListByRecordIds(bizProjectCheckRecordIds);
        }
        Map<Long,List<BizRectifyReview>> bizRectifyReviewMap = bizRectifyReviews.stream().collect(Collectors.groupingBy(BizRectifyReview::getRecordId));
        bizProjectCheckList.stream().forEach(item -> {
            List<TQualityFileItem> checkRecordList = bizProjectCheckRecordMap.get(item.getId());
            if(checkRecordList == null){
                checkRecordList = new ArrayList<>();
            }
            // 质量问题总数
            item.setHiddenDangerSum(checkRecordList.size());
            /*完成情况*/
            item.setHiddenAbarbeitung(checkRecordList.stream().filter(a -> a.getDataStatus().equals("2") ).toArray().length+"/"+checkRecordList.size());
            // 检查人数
            int rummagerCount = checkRecordList.stream().mapToInt(a ->{
                List<BizRectifyReview> bizRectifyReviewList = bizRectifyReviewMap.get(a.getId());
                if(bizRectifyReviewList != null){
                    return bizRectifyReviewList.stream().map(item1->item1.getOperatorer()).collect(Collectors.toSet()).size();
                }
                return 0;
            }).sum();
            item.setRummagerCount(rummagerCount);
            //发现隐患数
            if(checkRecordList.size() > 0){
                long findDangerCount = checkRecordList.stream().count();
                bizProjectCheck.setFindDangerCount(findDangerCount);
            }else {
                bizProjectCheck.setFindDangerCount((long) 0);
            }
            //检查类型
            CommonCheckType commonCheckType = commonCheckTypeMapper.selectCommonCheckTypeById(item.getCheckType());
            if(commonCheckType != null){
                List<String> checkNameList = new ArrayList<>();
                Arrays.asList(commonCheckType.getAncestors().split(",")).forEach(ancestor -> {//[5,502]
                    String checkTypeName = commonCheckTypeMapper.selectListTypeByTypeNo(Long.valueOf(ancestor)).getCheckTypeName();
                    checkNameList.add(checkTypeName);
                });
                item.setCheckTypeName(StringUtils.join(checkNameList,"/"));
            }

            //检查状态名称
            if(item.getStatus() != null){
                item.setCheckStatusName(DictUtils.getDictLabel(DictTypeConstants.CHECK_STATUS,item.getStatus()));
            }
            //是否有权限新增记录
            if(item.getCheckPeople() != null){
                List<String> checkPeoples = Arrays.asList(item.getCheckPeople().split(","));
                if(checkPeoples.contains(SecurityUtils.getUsername())){
                    item.setHasAddRecordPermission(true);
                }else{
                    item.setHasAddRecordPermission(false);
                }
            }
        });
        //创建人
        NameUtils.handleUserNameToNickName(bizProjectCheckList,sysUserMapper.selectUserListAll(),"createBy");
        return bizProjectCheckList;
    }


    @Override
    public List<BizProjectCheck> selectProjectCheckListForApp(BizProjectCheck bizProjectCheck,String userName) {
        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckMapper.selectBizProjectCheckListForApp(bizProjectCheck);
        PageUtils.clearPage();
        if(bizProjectCheckList.size() == 0){
            return new ArrayList<>();
        }
        List<CommonCheckType> commonCheckTypes = commonCheckTypeMapper.selectCommonCheckTypeList(new CommonCheckType());
        List<Long> bizProjectCheckIds = bizProjectCheckList.stream().map(item->item.getId()).collect(Collectors.toList());
        //查询相关的所有的记录并进行缓存
        List<BizProjectCheckRecord> bizProjectCheckRecords  = bizProjectCheckRecordMapper.selectBizProjectCheckRecordByTaskIds(bizProjectCheck.getProjectId(),bizProjectCheckIds,new ArrayList<>());
        Map<Long,List<BizProjectCheckRecord>> bizProjectCheckRecordMap = bizProjectCheckRecords.stream().collect(Collectors.groupingBy(BizProjectCheckRecord::getProjectCheckId));

        bizProjectCheckList.stream().forEach(item -> {
            List<BizProjectCheckRecord> checkRecordList = bizProjectCheckRecordMap.get(item.getId());
            if(checkRecordList == null){
                checkRecordList = new ArrayList<>();
            }
            // 隐患总数
            item.setHiddenDangerSum(checkRecordList.size());
            //拼接检查类型
            CommonCheckType commonCheckType = commonCheckTypes.stream().filter(commonCheckTypeItem->commonCheckTypeItem.getId().equals(item.getCheckType())).findFirst().get();
            if(commonCheckType != null){
                List<String> checkNameList = new ArrayList<>();
                Arrays.asList(commonCheckType.getAncestors().split(",")).forEach(checkTypeNo -> {
                    String checkTypeName = commonCheckTypes.stream().filter(commonCheckTypeItem->commonCheckTypeItem.getCheckTypeNo().equals(checkTypeNo)).findFirst().get().getCheckTypeName();
                    checkNameList.add(checkTypeName);
                });
                item.setCheckTypeName(StringUtils.join(checkNameList,"/"));
            }
            //检查依据名称
            if(item.getCheckAccording() != null){
                item.setCheckAccordingName(DictUtils.getDictLabel(DictTypeConstants.CHECK_ACCORDING,String.valueOf(item.getCheckAccording())));
            }
            //检查状态名称
            if(item.getStatus() != null){
                item.setCheckStatusName(DictUtils.getDictLabel(DictTypeConstants.CHECK_STATUS,item.getStatus()));
            }
            //是否有权限新增记录
            if(item.getCheckPeople() != null){
                List<String> checkPeoples = Arrays.asList(item.getCheckPeople().split(","));
                if(checkPeoples.contains(userName)){
                    item.setHasAddRecordPermission(true);
                }else{
                    item.setHasAddRecordPermission(false);
                }
            }
        });
        //创建人
        NameUtils.handleUserNameToNickName(bizProjectCheckList,sysUserMapper.selectUserListAll(),"createBy");
        return bizProjectCheckList;
    }

    /**
     * 新增项目自检
     *
     * @param bizProjectCheck 项目自检
     * @return 结果
     */
    @Override
    public int insertBizProjectCheck(BizProjectCheck bizProjectCheck)
    {
        //新增时状态改为“任务已下发”
        bizProjectCheck.setStatus("1");

        if(StringUtils.isNotNull(bizProjectCheck.getStartTime()) && StringUtils.isNotNull(bizProjectCheck.getEndTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //计划检查时间
            bizProjectCheck.setPlanCheckTime(simpleDateFormat.format(bizProjectCheck.getStartTime()) + "至" + simpleDateFormat.format(bizProjectCheck.getEndTime()));
        }
        bizProjectCheck.setCreateTime(DateUtils.getNowDate());
        bizProjectCheck.setCreateBy(SecurityUtils.getUsername());
        return bizProjectCheckMapper.insertBizProjectCheck(bizProjectCheck);
    }

    @Override
    public int insertBizProjectCheckNoLogin(BizProjectCheck bizProjectCheck) {
        //新增时状态改为“任务已下发”
        bizProjectCheck.setStatus("1");

        if(StringUtils.isNotNull(bizProjectCheck.getStartTime()) && StringUtils.isNotNull(bizProjectCheck.getEndTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //计划检查时间
            bizProjectCheck.setPlanCheckTime(simpleDateFormat.format(bizProjectCheck.getStartTime()) + "至" + simpleDateFormat.format(bizProjectCheck.getEndTime()));
        }
        bizProjectCheck.setCreateTime(DateUtils.getNowDate());
        return bizProjectCheckMapper.insertBizProjectCheck(bizProjectCheck);
    }

    /**
     * 修改项目自检
     *
     * @param bizProjectCheck 项目自检
     * @return 结果
     */
    @Override
    public int updateBizProjectCheck(BizProjectCheck bizProjectCheck)
    {
        if(StringUtils.isNotNull(bizProjectCheck.getStartTime()) && StringUtils.isNotNull(bizProjectCheck.getEndTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //计划检查时间
            bizProjectCheck.setPlanCheckTime(simpleDateFormat.format(bizProjectCheck.getStartTime()) + "至" + simpleDateFormat.format(bizProjectCheck.getEndTime()));
        }
        //如果状态为“任务已结束”，设置完成时间
        if("3".equals(bizProjectCheck.getStatus())){
            bizProjectCheck.setComplateCheckTime(DateUtil.date());
        }
        bizProjectCheck.setUpdateTime(DateUtils.getNowDate());
        bizProjectCheck.setUpdateBy(SecurityUtils.getUsername());
        return bizProjectCheckMapper.updateBizProjectCheck(bizProjectCheck);
    }

    @Override
    public int updateBizProjectCheckNoLogin(BizProjectCheck bizProjectCheck) {
        if(StringUtils.isNotNull(bizProjectCheck.getStartTime()) && StringUtils.isNotNull(bizProjectCheck.getEndTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //计划检查时间
            bizProjectCheck.setPlanCheckTime(simpleDateFormat.format(bizProjectCheck.getStartTime()) + "至" + simpleDateFormat.format(bizProjectCheck.getEndTime()));
        }
        //如果状态为“任务已结束”，设置完成时间
        if("3".equals(bizProjectCheck.getStatus())){
            bizProjectCheck.setComplateCheckTime(DateUtil.date());
        }
        bizProjectCheck.setUpdateTime(DateUtils.getNowDate());
        return bizProjectCheckMapper.updateBizProjectCheck(bizProjectCheck);
    }

    /**
     * 批量删除项目自检
     *
     * @param ids 需要删除的项目自检主键
     * @return 结果
     */
    @Override
    public int deleteBizProjectCheckByIds(Long[] ids)
    {
        return bizProjectCheckMapper.deleteBizProjectCheckByIds(ids);
    }

    /**
     * 删除项目自检信息
     *
     * @param id 项目自检主键
     * @return 结果
     */
    @Override
    public int deleteBizProjectCheckById(Long id)
    {
        return bizProjectCheckMapper.deleteBizProjectCheckById(id);
    }

    @Override
    public int selectCount(ListRequestVo listRequestVo) {
        return bizProjectCheckMapper.selectCount(listRequestVo);
    }
    @Override
    public int updateProjectCheckStatus(BizProjectCheck bizProjectCheck) {
        return bizProjectCheckMapper.updateBizProjectCheck(bizProjectCheck);
    }

    @Override
    public BizProjectCheck selectListByCheckId(Long projectCheckId) {
        return bizProjectCheckMapper.selectListByCheckId(projectCheckId);
    }

    @Override
    public Long countByStatisticsDto(StatisticsDto statisticsDto) {
        Long count = bizProjectCheckMapper.countByStatisticsDto(statisticsDto);
        return count;
    }

    @Override
    public List<BizProjectCheck> selectProjectCheckListForQuality(BizProjectCheck bizProjectCheck) {
        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckMapper.selectBizProjectCheckListForApp(bizProjectCheck);
        PageUtils.clearPage();
        if(bizProjectCheckList.size() == 0){
            return new ArrayList<>();
        }
        List<CommonCheckType> commonCheckTypes = commonCheckTypeMapper.selectCommonCheckTypeList(new CommonCheckType());
        List<Long> bizProjectCheckIds = bizProjectCheckList.stream().map(item->item.getId()).collect(Collectors.toList());
        //查询相关的所有的记录并进行缓存
        List<TQualityFileItem> qualityProjectCheckRecords  = tQualityFileItemMapper.qualityList(bizProjectCheck.getProjectId(),bizProjectCheckIds);
        Map<Long,List<TQualityFileItem>> bizProjectCheckRecordMap = qualityProjectCheckRecords.stream().collect(Collectors.groupingBy(TQualityFileItem::getFileId));

        bizProjectCheckList.stream().forEach(item -> {
            List<TQualityFileItem> checkRecordList = bizProjectCheckRecordMap.get(item.getId());
            if(checkRecordList == null){
                checkRecordList = new ArrayList<>();
            }
            // 隐患总数
            item.setHiddenDangerSum(checkRecordList.size());
            item.setHiddenAbarbeitung(checkRecordList.stream().filter(a -> a.getDataStatus().equals("2") ).toArray().length+"/"+checkRecordList.size());
            //拼接检查类型
            CommonCheckType commonCheckType = commonCheckTypes.stream().filter(commonCheckTypeItem->commonCheckTypeItem.getId().equals(item.getCheckType())).findFirst().get();
            if(commonCheckType != null){
                List<String> checkNameList = new ArrayList<>();
                Arrays.asList(commonCheckType.getAncestors().split(",")).forEach(checkTypeNo -> {
                    String checkTypeName = commonCheckTypes.stream().filter(commonCheckTypeItem->commonCheckTypeItem.getCheckTypeNo().equals(checkTypeNo)).findFirst().get().getCheckTypeName();
                    checkNameList.add(checkTypeName);
                });
                item.setCheckTypeName(StringUtils.join(checkNameList,"/"));
            }
            //检查依据名称
            if(item.getCheckAccording() != null){
                item.setCheckAccordingName(DictUtils.getDictLabel(DictTypeConstants.CHECK_ACCORDING,String.valueOf(item.getCheckAccording())));
            }
            //检查状态名称
            if(item.getStatus() != null){
                item.setCheckStatusName(DictUtils.getDictLabel(DictTypeConstants.CHECK_STATUS,item.getStatus()));
            }
            //是否有权限新增记录
            if(item.getCheckPeople() != null){
                List<String> checkPeoples = Arrays.asList(item.getCheckPeople().split(","));
                if(checkPeoples.contains(bizProjectCheck.getUserName())){
                    item.setHasAddRecordPermission(true);
                }else{
                    item.setHasAddRecordPermission(false);
                }
            }
        });
        //创建人
        NameUtils.handleUserNameToNickName(bizProjectCheckList,sysUserMapper.selectUserListAll(),"createBy");
        return bizProjectCheckList;
    }

    @Override
    public int splitFiles(List<TQualityFileItem> listFileItems) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String fileId = "";
        if (listFileItems.size() > 0)
        {
            TQualityFileItem item = listFileItems.get(0);
            BizProjectCheck bizProjectCheck = new BizProjectCheck();
            bizProjectCheck.setId(item.getFileId());
            bizProjectCheck.setUserName(loginUser.getUser().getUserName());
            /*任务进行中*/
            bizProjectCheck.setStatus("2");
            Integer nSize = bizProjectCheckMapper.updateBizProjectCheck(bizProjectCheck);
            for(TQualityFileItem t :listFileItems){
                t.setCheckPeopleId(String.valueOf(loginUser.getUserId()));
            }
            fileId = String.valueOf(item.getFileId());
            return iTQualityFileService.splitFileNew(listFileItems,fileId);
        }
        else
        {
            return 0;
        }
    }

    @Override
    public List<TQualityFileItem> getQualityProblemList(String fileId) {
        TQualityFileItem t = new TQualityFileItem();
        t.setFileId(Long.parseLong(fileId));
        return tQualityFileItemMapper.selectCheckLedger(t);
    }
}
